<template>
  <div class="components-container">
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-row>
      <el-col :span="20">
        <el-form-item label="岗位名称">
          <el-input v-model="formInline.roleName" :clearable="true" placeholder="请输入岗位名称"></el-input>
        </el-form-item>
         <el-form-item label="职位">
          <template>
            <el-select v-model="formInline.position" clearable placeholder="请选择">
              <el-option
                v-for="item in positionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="状态">
          <template>
            <el-select v-model="formInline.status" clearable placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryList" size="medium" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="4" style="text-align:right;"><el-button type="primary" size="medium" icon="el-icon-plus" @click="added" v-show="showAdd">新增</el-button></el-col>
    </el-row>
  </el-form>

      <template>
        <el-table v-loading="loading" class="fns-table" :data="tableData" border style="width: 100%">
          <el-table-column prop="name" align="center" label="岗位名称" min-width="140"></el-table-column>
          <el-table-column prop="desc" align="center" label="岗位描述" min-width="300"></el-table-column>
          <el-table-column align="center" label="职位" min-width="100">
            <template slot-scope="scope">
              <span>{{scope.row.position == 'OTHER'?'普通用户': scope.row.position == 'SALESMAN'?'销售':'销售组长'}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态">
            <template slot-scope="scope">
              <span>{{scope.row.status?'启用':'停用'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updatedOn" align="center" label="修改日期" min-width="160"></el-table-column>
          <el-table-column align="center" min-width="100" label="操作">
            <template slot-scope="scope">
            <el-tooltip content="修改" placement="top" v-show="showUpdate">
              <a @click="edit(scope.$index, scope.row)" style="margin-right:10px;">
                <i class="el-icon-edit-outline"></i>
              </a>
            </el-tooltip>
            <el-tooltip content="通知设置" placement="top" v-show="showNotice">
              <a @click="setup(scope.$index, scope.row)">
                <i class="el-icon-setting"></i>
              </a>
            </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- ========分页======-->
    <pages v-on:_pageChange="_pageChange" :total="total"></pages>
      

      <!-- ========弹窗======-->
      <el-dialog
        title="新增岗位"
        class="fns-el-dialog-md"
        :visible.sync="dialogVisible"
        width="580px"
        :before-close="handleClose"
        :close-on-click-modal="false">
        <el-form class="dialogmain" label-width="100px" style="margin-left:6px;padding-right:20px;" :model="formAdd" ref="formAdd" :rules="rules">
          <el-form-item label="岗位名称：" prop="name">
            <el-input v-model="formAdd.name" :maxlength="20" placeholder="请输入岗位名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="岗位说明：">
            <el-input v-model="formAdd.remark" type="textarea" :maxlength="300" :rows="2" placeholder="请输入岗位说明(选填)" clearable></el-input>
          </el-form-item>
          <el-form-item label="职位：">
            <template>
              <el-radio-group v-model="formAdd.position">
                <el-radio label="OTHER">普通用户</el-radio>
                <el-radio label="SALESMAN">销 售</el-radio>
                <el-radio label="SALESMAN_LEADER">销售组长</el-radio>
              </el-radio-group>
             </template>
          </el-form-item>
           <el-form-item label="状态：">
              <el-radio-group v-model="formAdd.status">
                <el-radio :label="1">启 用</el-radio>
                <el-radio :label="0">停 用</el-radio>
              </el-radio-group>
            </el-form-item>
          <el-form-item label="权限分配：" class="redx">
            <el-tree
              :data="obj"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              v-model="formAdd.resourceIds"
              @check="checkeds">
            </el-tree>
          </el-form-item>
          <div v-if='cheakShow' style="color:#f56c6c;padding-left:110px; z-index:1000; position:relative;">权限不能为空</div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAdd()">提 交</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="修改岗位"
        :visible.sync="dialogEdit"
        class="fns-el-dialog-md"
        width="580px"
        :before-close="handleClose"
        :close-on-click-modal="false">
        <el-form class="dialogmain" label-width="100px" style="margin-left:6px;padding-right:20px;" :model="formEdit" ref="formEdit" :rules="rulesEdit">
          <el-form-item label="岗位名称：" prop="name">
            <el-input v-model="formEdit.name" :maxlength="20" placeholder="请输入岗位名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="岗位说明：">
            <el-input v-model="formEdit.remark" type="textarea" :maxlength="300" :rows="2" placeholder="请输入岗位说明(选填)" clearable></el-input>
          </el-form-item>
          <el-form-item label="职位：">
            <template>
              <el-radio-group v-model="formEdit.position">
                <el-radio label="OTHER">普通用户</el-radio>
                <el-radio label="SALESMAN">销 售</el-radio>
                <el-radio label="SALESMAN_LEADER">销售组长</el-radio>
              </el-radio-group>
             </template>
          </el-form-item>
           <el-form-item label="状态：">
              <el-radio-group v-model="formEdit.status">
                <el-radio :label="1">启 用</el-radio>
                <el-radio :label="0">停 用</el-radio>
              </el-radio-group>
            </el-form-item>
          <el-form-item label="权限分配：" class="redx">
            <el-tree
              :data="obj"
              ref="tree"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              :default-expanded-keys="formEdit.expandedkeys"
              :default-checked-keys='formEdit.checkedKey'
              v-model="formEdit.resourceIds" 
              @check="checkeds">
            </el-tree>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogEdit = false">取 消</el-button>
          <el-button type="primary" @click="handleEdit()">提 交</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="通知设置"
        :visible.sync="settingVisible"
        width="900px"
        :before-close="handleClose"
        :close-on-click-modal="false">
        <el-form style="margin-left:6px;" :model="formSetting">
          <el-col :span="24" :offset="1">
            <el-form-item>
              <el-checkbox-group v-model="formSetting.notificationIds" @change="handleChange">
                <el-checkbox 
                v-for="(item, index) in noticeOptions" 
                :label="item.id" 
                :value="item.value"
                :key="item.id"
                style='width:275px;'>
                {{item.title}}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="settingVisible = false">取 消</el-button>
          <el-button type="primary" @click="setting('formSetting')">提 交</el-button>
        </span>
      </el-dialog>

  </div>
</template>

<script>
import { Message } from 'element-ui'
import * as api from '@/api/system'
import pages from '../../components/page/page'
import { findMenu, findSubMenu, findBtn } from '@/utils/btn'
export default {
  data() {
    return {
      cheakShow: false,
      loading: false,
      page: {
        index: 1,
        size: 10
      },
      total: 0,
      dialogVisible: false,
      settingVisible: false,
      dialogEdit: false,
      formInline: {
        // roleName: '',
        position: '',
        status: ''
      },
      positionOptions: [{
        value: 'OTHER',
        label: '普通用户'
      }, {
        value: 'SALESMAN',
        label: '销售'
      }, {
        value: 'SALESMAN_LEADER',
        label: '销售组长'
      }],
      options: [{
        value: '1',
        label: '启用'
      }, {
        value: '0',
        label: '停用'
      }],
      obj: [],
      checkList: [],
      noticeOptions: [],
      tableData: [],
      formAdd: {
        name: '',
        remark: '',
        resourceIds: [],
        position: 'OTHER',
        status: 1
      },
      formEdit: {
        name: '',
        remark: '',
        resourceIds: [],
        position: 'OTHER',
        status: '',
        checkedkey: [],
        expandedkeys: []
      },
      formSetting: {
        notificationIds: [],
        roleId: ''
      },
      defaultProps: {
        children: 'children',
        // id: 'id',
        label: 'displayName'
      },
      modelData: [],
      count: 1,
      rules: {
        name: [
          { required: true, message: '岗位不能为空', trigger: 'blur' },
          { max: 20, message: '长度最多不能超过20 个字符', trigger: 'blur' }
        ],
        resourceIds: [
          { required: true, message: '权限不能为空', trigger: 'blur' },
        ]
      },
      rulesEdit: {
        name: [
          { required: true, message: '岗位不能为空', trigger: 'blur' },
          { max: 20, message: '长度最多不能超过20 个字符', trigger: 'blur' }
        ],
        resourceIds: [
          { required: true, message: '权限不能为空', trigger: 'change' },
        ]
      }
    }
  },
  components: {
    pages
  },
  created() {
    this.queryList()
    // 初始化所有通知
    api.allNotifications().then((res) => {
      this.noticeOptions = res.data
    })
    var d = []
    api.resourceList().then((res) => {
      d = res.data
      this.obj = this.getTree(d, 1, 'id', 'parentId', 'children')
    })
    // console.log(this.getTree(this.obj, 0, 'id', 'parentId', 'children', 'sortNo', 'displayName', 'extData'))
  },
  computed: {
    showAdd() {
      let menu = findMenu('系统管理')
      let subMenu = findSubMenu(menu.children, '岗位管理')
      if (findBtn(subMenu.children, '新增')) {
        return true
      } else {
        return false
      }
    },
    showUpdate() {
      let menu = findMenu('系统管理')
      let subMenu = findSubMenu(menu.children, '岗位管理')
      if (findBtn(subMenu.children, '修改')) {
        return true
      } else {
        return false
      }
    },
    showNotice() {
      let menu = findMenu('系统管理')
      let subMenu = findSubMenu(menu.children, '岗位管理')
      if (findBtn(subMenu.children, '通知设置')) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    // 分页和列表
    _pageChange(val, flag) {
      var arr = []
      if (flag === 'size') {
        this.page.index = val
        this.queryList()
      } else {
        arr.push(val)
        this.page.index = 1
        this.page.size = arr[0]
        this.queryList()
      }
    },
    handleChange() {
      // console.log(this.formSetting.notificationIds)
    },
    // 获取列表信息
    queryList(val) {
      this.loading = true
      var pages = {
        index: this.page.index,
        size: this.page.size || val
      }
      var data = Object.assign({}, this.formInline, pages)
      api.roleList(data).then((res) => {
        if (+res.code === 0) {
          this.tableData = res.data.rows
          this.total = +res.data.total
        }
        this.loading = false
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },
    getTree(data, root, idTxt = 'id', pidTxt = 'pid', pushTxt = 'children') {
      let getNode = (id) => {
        let node = []
        data.forEach((val, key, arr) => {
          if (data[key][pidTxt] == id) {
            data[key][pushTxt] = getNode(data[key][idTxt])
            node = [...node, data[key]]
          }
        })
        // console.log(node)
        return node.length > 0 ? node : []
      }
      return getNode(root)
    },
    // 点击弹出新增窗口
    added() {
      this.modalTitle = '新增'
      this.dialogVisible = true
      this.formAdd.name = ''
      this.formAdd.remark = ''
      this.formAdd.position = 'OTHER'
      this.formAdd.resourceIds = []
      this.formAdd.status = 1
      // this.$set(this.formAdd, 'name', '');
      // this.$set(this.formAdd, 'remark', '');
      // this.$set(this.formAdd, 'position', 'OTHER');
      this.$set(this.formAdd, 'resourceIds', []);
      // this.$set(this.formAdd, 'status', 1);
    },
    // 修改和新增提交
    // handleSubmit() {
    //   if (this.formAdd.id) {
    //     api.roleUpdate(this.formAdd).then(res => {
    //       if (+res.code === 0) {
    //         this.formAdd = {}
    //         this.queryList()
    //         this.dialogVisible = false
    //       }
    //     }).catch(error => {
    //       this.loading = false
    //     })
    //   } else {
    //     api.roleAdd(this.formAdd.id).then(res => {
    //       if (+res.code === 0) {
    //         this.formAdd = {}
    //         this.queryList()
    //         this.dialogVisible = false
    //       }
    //     }).catch(error => {
    //       this.dialogVisible = false
    //       this.loading = false
    //     })
    //   }
    // },
    // 新增提交
    checkeds(a, b){
        var id = b.checkedKeys
        this.formAdd.resourceIds = id
        this.formEdit.resourceIds = id
        if (this.formAdd.resourceIds === '' || this.formAdd.resourceIds.length === 0) {
          this.cheakShow = true
        } else {
          this.cheakShow = false
        }
        
    },
    handleAdd() {
      if (this.formAdd.resourceIds === '' || this.formAdd.resourceIds.length === 0) {
          this.cheakShow = true
          return
        } else {
          this.cheakShow = false
        }
      this.$refs['formAdd'].validate((valid) => {
        if (valid) {
          api.roleAdd(this.formAdd).then(res => {
            if (+res.code === 0) {
              this.formAdd = {}
              this.queryList()
              this.dialogVisible = false
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          return
        }
      })
    },
    setCheckedKeys(resourceIds) {
      this.$refs.tree.setCheckedKeys(resourceIds);
    },
    // 根据ID获取岗位信息
    edit(index, row) {
      this.dialogEdit = true
      const id = { id: row.id }
      this.formEdit.id = row.id
      api.getDetail(id).then((res) => {
        if (+res.code === 0) {
          var rowData = res.data
          this.formEdit.id = rowData.id || ''
          this.formEdit.name = rowData.name || ''
          this.formEdit.remark = rowData.remark || ''
          this.formEdit.position = rowData.position || ''
          this.formEdit.checkedkey = rowData.resourceIds
          this.formEdit.expandedkeys = rowData.resourceIds
          // this.formEdit.checkedkey = ['3','4']
          this.formEdit.status = Number(rowData.status || '')
          this.setCheckedKeys(rowData.resourceIds)
        }
      })
      // this.$set(this.formEdit, 'resourceIds', []);
      // this.$set(this.formEdit, 'checkedKey', []);
      // this.$set(this.formEdit, 'expandedkeys', []);
      // this.formEdit.expandedkeys = []
    },
    // 修改提交
    handleEdit() {
      // if (this.formEdit.resourceIds === '' || this.formEdit.resourceIds.length === 0) {
      //     this.cheakShow = true
      //     return
      //   } else {
      //     this.cheakShow = false
      //   }
      this.$refs['formEdit'].validate((valid) => {
        if (valid) {
          delete this.formEdit.checkedkey
          delete this.formEdit.expandedkeys
          var data = this.formEdit
          api.roleUpdate(this.formEdit).then(res => {
            if (+res.code === 0) {
              this.dialogEdit = false
              this.queryList()
              this.$message({
                message: '修改成功',
                type: 'success',
                showClose: true
              })
            }
          }).catch(err => {
            this.$message({
              message: '修改失败',
              type: 'error',
              showClose: true
            })
          })
        }
      })
    },
    // 通过ID获取关联的通知
    setup(index, row) {
      this.modalTitle = '通知设置'
      this.settingVisible = true
      var id = { id: row.id }
      this.formSetting.roleId = row.id
      api.linked(id).then((res) => {
        if (+res.code === 0) {
          var rowData = res.data
          this.formSetting.notificationIds.push(rowData)
          this.formSetting.notificationIds = rowData || []
        }
      })
    },
    post(va) {
      if (+va === 1) {
        return ['后台管理', '款项确认']
      }
    },
    // 通知设置提交
    setting() {
      if (this.formSetting) {
        api.roleSetup(this.formSetting).then((res) => {
          Message({
            message: '设置成功',
            type: 'success',
            duration: 5 * 1000
          })
          this.settingVisible = false
          this.queryList()
          return
        })
      } else {
        Message({
          message: '设置失败',
          type: 'success',
          duration: 5 * 1000
        })
      }
    },
    handleClose(done) {
      this.dialogVisible = false
      this.settingVisible = false
      this.dialogEdit = false
    }
  }
}
</script>
<style>
/*.components-container {
    position: relative;
    height: 89vh;
    overflow-y: scroll;
  }*/
  /*.dialogmain{max-height:325px; overflow-y:auto;padding-right: 20px;}*/
  .el-checkbox{margin-left: 0px; margin-right:0px;margin-left: 0px;}
  .el-checkbox+.el-checkbox{margin-right:0px!important;margin-left: 0px;}
  .el-col-offset-1{margin-left: 0;}
  .el-tree{margin-top:10px;}
  .fns-el-dialog-md .el-dialog .el-dialog__body{max-height:483px!important;}
  .fns-el-dialog-md .el-dialog .el-form{max-height:483px!important;}
  .redx .el-form-item__label:before {
      content: ' * '!important;
      color: red!important;
    }
</style>
